<?php

namespace app\controller\api\activity;

use app\common\repositories\activity\lottery\LuckLotteryRecordRepository;
use app\common\repositories\wechat\WechatQrcodeRepository;
use app\common\repositories\wechat\WechatUserRepository;
use app\Request;
use think\App;
use app\common\repositories\activity\lottery\LuckLotteryRepository;
use crmeb\basic\BaseController;

class LuckLottery extends BaseController
{
    /**
     * @var repository
     */
    protected $repository;

    /**
     * @param App $app
     * @param repository $repository
     */
    public function __construct(App $app, LuckLotteryRepository $repository)
    {
        parent::__construct($app);
        $this->repository = $repository;
    }

    /**
     * @param Request $request
     * @param $factor
     * @return mixed
     * @throws \Psr\SimpleCache\InvalidArgumentException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @author: fupeng
     * @day: 2024/3/28
     * 抽奖活动信息
     */
    public function LotteryInfo(Request $request, $factor)
    {
        if (!$factor) $factor = 1;
        $lottery = $this->repository->getFactorLotteryCache((int)$factor);

        if (!$lottery) {
            return app('json')->fail('抽奖活动不存在');
        }
        $uid = (int)$request->uid();

        $prizeArr = isset($lottery['prize']) && $lottery['prize'] ? $lottery['prize'] : [];
        $prize = [];
        if ($prizeArr) {
            foreach ($prizeArr as &$item) {
                $prize[] = [
                    'id' => $item['id'],
                    'type' => $item['type'],
                    'name' => $item['name'],
                    'image' => $item['image'],
                    'prompt' => $item['prompt'],
                ];
            }
        }
        $lottery['prize'] = $prize;
        $lotteryData = ['lottery' => $lottery];
        $this->repository->checkoutUserAuth($uid, (int)$lottery['id'], [], $lottery);
        $lotteryData['lottery_num'] = $this->repository->getLotteryNum($uid, (int)$lottery['id'], [], $lottery);
        $all_record = $user_record = [];
        $lotteryRecordServices = app()->make(LuckLotteryRecordRepository::class);

        if ($lottery['is_all_record'] || $lottery['is_personal_record']) {
            if ($lottery['is_all_record']) {
                $all_record = $lotteryRecordServices->getWinList(['lottery_id' => $lottery['id']]);
            }
            if ($lottery['is_personal_record']) {
                $user_record = $lotteryRecordServices->getWinList(['lottery_id' => $lottery['id'], 'uid' => $uid]);
            }
        }

        if ($lottery['factor'] == 1) {//积分抽奖
            $data = $lotteryRecordServices->getLotteryNum($uid, (int)$lottery['id']);
            $lotteryData['todayCount'] = (int)max(bcsub((string)$lottery['lottery_num'], (string)$data['todayCount'], 0), 0);
            $lotteryData['totalCount'] = (int)max(bcsub((string)$lottery['total_lottery_num'], (string)$data['totalCount'], 0), 0);
        } else {
            $lotteryData['totalCount'] = $lotteryData['todayCount'] = $lotteryData['lottery_num'] = (int)$lotteryData['lottery_num'];
        }
        $lotteryData['integral'] = $request->userInfo()->integral;
        $lotteryData['all_record'] = $all_record;
        $lotteryData['user_record'] = $user_record;
        $lotteryData['cache_time'] = in_array($factor, [3, 4]) ? $this->repository->getCacheLotteryExpireTime($uid, $factor == 3 ? 'order' : 'comment') : 0;
        return app('json')->success('ok', $lotteryData);
    }

    /**
     * @return mixed
     * @throws \Psr\SimpleCache\InvalidArgumentException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @author: fupeng
     * @day: 2024/3/28
     * 参与抽奖
     */
    public function luckLottery()
    {
        $id = $this->request->param('id', 0);
        $type = $this->request->param('type', 0);
        $userInfo = $this->request->userInfo();
        $uid = $userInfo->uid;
        $isWechat = $this->request->isWechat();
        if ($type == 5 && $isWechat && $userInfo->wechat_user_id > 0) {
            $wechat = app()->make(WechatUserRepository::class);
            $subscribe = $wechat->get(['user_type' => 'wechat', 'wechat_user_id' => $userInfo->wechat_user_id, 'subscribe' => 1]);
            if (!$subscribe) {
                $url = '';
                $qrcodeService = app()->make(WechatQrcodeRepository::class);
                $url = $qrcodeService->getTemporaryQrcode('luckLottery-'. $uid, $uid)->url;
                return app('json')->success('请先关注公众号', ['code' => 'subscribe', 'url' => $url]);
            }
        }
        if (!$id) {
            return app('json')->fail('参数错误');
        }
        return app('json')->success($this->repository->luckLottery($uid, $id));
    }

    /**
     * @param LuckLotteryRecordRepository $repository
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @author: fupeng
     * @day: 2024/3/28
     * 领取奖品
     */
    public function lotteryReceive(LuckLotteryRecordRepository $repository)
    {

        $id = $this->request->param('id', 0);
        $name = $this->request->param('name', '');
        $phone = $this->request->param('phone', '');
        $address = $this->request->param('address', '');
        $mark = $this->request->param('mark', '');
        if (!$id) {
            return app('json')->fail('参数错误');
        }
        $uid = (int)$this->request->uid();
        return app('json')->success($repository->receivePrize($uid, $id, compact('name', 'phone', 'address', 'mark')) ? '领取成功' : '领取失败');
    }

    /**
     * @param Request $request
     * @return mixed
     * @author: fupeng
     * @day: 2024/3/27
     * 获取中奖记录
     */
    public function lotteryRecord(Request $request,LuckLotteryRecordRepository $repository)
    {
        $uid = (int)$request->uid();
        [$page, $limit] = $this->getPage();
        return app('json')->success($repository->getRecord($uid,[],$page,$limit));
    }

}
